package me.shan.data.structure;

import java.util.List;

/**
 * 描述：使用栈实现的链表
 *
 * @author liuchuang
 * @date 2021/7/7 16:48
 */
public class StackQueue {

    /**
     * 新增元素时push入该栈
     */
    private final ArrayStack addStack;

    /**
     * 删除元素时从该栈pop出元素
     */
    private final ArrayStack removeStack;

    public StackQueue() {
        addStack = new ArrayStack();
        removeStack = new ArrayStack();
    }

    /**
     * 添加元素
     *
     * @param value 值
     */
    public void add(int value) throws Exception {
        addStack.push(value);
    }

    /**
     * 链表删除表头元素
     *
     * @return 被删除的元素
     * @throws Exception 空链表不允许删除
     */
    public int remove() throws Exception {
        // 当弹出栈无元素时，需要将插入栈中的元素加入到弹出栈中
        if (removeStack.getSize() == 0) {
            if (addStack.getSize() == 0) {
                throw new Exception("链表为空，不允许remove操作");
            }
            while (addStack.getSize() > 0) {
                removeStack.push(addStack.pop());
            }
        }
        return removeStack.pop();
    }

    @Override
    public String toString() {
        List<Integer> removeList = removeStack.getElementList();
        List<Integer> addList = addStack.getElementList();
        // 顺序需要按照pop顺序来打印，所以removeList需要逆序遍历，addList需要顺序遍历
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("StackQueue{");
        if (removeList.size() == 0 && addList.size() == 0) {
            stringBuilder.append(" null ");
        }
        if (removeList.size() > 0) {
            for (int i = removeList.size() - 1; i >= 0; i--) {
                stringBuilder.append(" ").append(removeList.get(i)).append(',');
            }
        }
        if (addList.size() > 0) {
            for (Integer integer : addList) {
                stringBuilder.append(" ").append(integer).append(',');
            }
        }
        stringBuilder.append('}');
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {
        StackQueue queue = new StackQueue();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        System.out.println(queue);
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        queue.add(5);
        queue.add(6);
        System.out.println(queue);
        queue.remove();
        queue.remove();
        queue.remove();
        queue.remove();
        System.out.println(queue);
        try {
            queue.remove();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
